package com.xzx.springbootredis.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.xzx.springbootredis.entity.ApiAccount;
import com.xzx.springbootredis.service.ApiAccountService;
import com.xzx.springbootredis.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * api account控制器
 */
@RestController
@RequestMapping("api_account")
public class ApiAccountController {
    @Autowired
    private ApiAccountService apiAccountService;
    @Value("${salt}")
    private String salt;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //注册账号
    @PostMapping("register")
    public JsonResult register(@RequestBody ApiAccount account){
        if(account.getAccount() == null || account.getAccount().trim().isEmpty()){
            return JsonResult.failed("账号名不能为空");
        }
        if (account.getPassword() == null || account.getPassword().trim().isEmpty()){
            return JsonResult.failed("密码不能为空");
        }
        //验证账号重复性
        ApiAccount accountInfo = apiAccountService.findByAccount(account.getAccount());
        if(accountInfo != null){
            return JsonResult.failed("该账号已经存在，重新输入.");
        }
        //密码md5加密
        String safePassword =  SecureUtil.md5(account.getPassword());
        account.setPassword(safePassword);
        int result = apiAccountService.addApiAccount(account);
        if(result == 0){
            return JsonResult.failed("注册失败");
        }
        return JsonResult.success("注册成功",null);
    }

    @PostMapping("login")
    public JsonResult login(@RequestBody ApiAccount account){
        if(account.getAccount() == null || account.getAccount().trim().isEmpty()){
            return JsonResult.failed("账号名不能为空");
        }

        if (account.getPassword() == null || account.getPassword().trim().isEmpty()){
            return JsonResult.failed("密码不能为空");
        }
        ApiAccount accountInfo = apiAccountService.findByAccount(account.getAccount());
        System.out.println(accountInfo);
        if(accountInfo == null || !accountInfo.getPassword().equals(SecureUtil.md5(account.getPassword()))){
            return JsonResult.failed("账号或密码输入错误.");
        }
        //生成token,返回给前端
        //生成规则，sha256(盐值+密码+时间)
        String token = SecureUtil.sha256(salt + account.getPassword()+ DateUtil.now());
        //使用reddis存储,k,v字符串
        stringRedisTemplate.opsForValue().set(token,token,24*60, TimeUnit.MINUTES);
        return JsonResult.success("登录成功",token);
    }
}
